<template>
  <view class="page">
    <view class="login-con">
      <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
        <u-avatar :src="avatar" size="77"></u-avatar>
      </button>
      <view class="color-info mt20">点击申请授权头像</view>
      <view class="w">
        <button class="btn-con" type="primary" @tap="tapLogin">登录</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import loginApi from '@/api/loginApi'

const avatar = ref('')
const onChooseAvatar = (e: any) => {
  const { avatarUrl } = e.detail
  avatar.value = avatarUrl
}

const openid = ref()
const tapLogin = () => {
  if (avatar.value == '') {
    uni.showToast({
      title: '请先授权头像',
      icon: 'none',
    })
    return
  }
  uni.login({
    provider: 'weixin',
    success: (res) => {
      loginApi
        .wxLogin({
          code: res.code,
        })
        .then((r: any) => {
          openid.value = r.data
          if (r.user) {
            uni.setStorageSync('userId', r.user.id)
            uni.switchTab({ url: '/pages/tabbar/index' })
          } else {
            // uni.navigateTo({
            //   url: '/pages/login/register',
            // })
            /* 不跳注册页  走接口直接注册 默认随机生成昵称 */
            rigister()
          }
        })
    },
    fail: (error) => {},
  })
}
const rigister = () => {
  loginApi
    .register({
      userName: generateRandomString(6),
      openId: openid.value,
      avatar: avatar.value,
    })
    .then((res: any) => {
      if (res.success) {
        uni.setStorageSync('userId', res.data.userId)
        uni.switchTab({ url: '/pages/tabbar/index' })
      }
    })
}
/* 随机生成昵称 */
const generateRandomString = (length: number) => {
  const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * charset.length)
    result += charset.charAt(randomIndex)
  }
  return result
}
</script>

<style lang="scss" scoped>
// button {
//   transform: scale(0.8);
//   border-radius: 30px;
// }

.page {
  background: #fff;
  height: 100vh;

  .login-con {
    text-align: center;

    .avatar-wrapper {
      padding: 0;
      width: 150rpx;
      height: 150rpx;
      margin-top: 200rpx;
      border-radius: 50%;
      background-color: #fff;
      border: none;
      image {
        width: 100%;
        height: 100%;
      }
    }

    .btn-con {
      margin-top: 200rpx;
    }
  }
}
</style>
